package com.oe.vdi.ui;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class JniSurfaceView extends SurfaceView
        implements SurfaceHolder.Callback2 {

    private static final String LOG_TAG = "OEView";

    protected static SurfaceHolder surfaceHolder;

    public JniSurfaceView(Context context) {
        super(context);
        init();
    }

    public JniSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public JniSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private Handler handler = new Handler();
    private Runnable myRunnable = new Runnable() {
        public void run() {
            reDraw();
            handler.post(this);
        }
    };

    void init() {
        this.setWillNotCacheDrawing(true);
        this.setWillNotDraw(true);
        surfaceHolder = getHolder();
        surfaceHolder.setFormat(2);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceHolder.addCallback(this);
        surfaceHolder.setKeepScreenOn(true);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setKeepScreenOn(true);
        setDrawingCacheEnabled(false);
        handler.post(myRunnable);
        Log.i(LOG_TAG, "init");
    }

    boolean isAttached = false;

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.i(LOG_TAG, "surfaceChanged");
        if (isAttached) {
            detachSurface();
            isAttached = false;
        }
        attachSurface(holder.getSurface());
        isAttached = true;
        onRedrawNeeded();
        reDraw();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.i(LOG_TAG, "surfaceCreated");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(LOG_TAG, "surfaceDestroyed");
        detachSurface();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        detachSurface();
    }


    static {
        System.loadLibrary("oe_egl");
    }

    public native void attachSurface(Surface sf);

    public native void detachSurface();

    public native void reDraw();

    @Override
    public void surfaceRedrawNeeded(SurfaceHolder holder) {
        Log.e(LOG_TAG, "surfaceRedrawNeeded");
        onRedrawNeeded();
        reDraw();
    }

    public void onRedrawNeeded() {
        Log.e(LOG_TAG, "onRedrawNeeded");
    }

}
